package com.controller;

/**
 * Created by wlc on 2018/4/14.
 */

import com.dao.QmDao;
import com.entity.UserMetadata;
import com.service.QmOperator;
import com.service.UserOperator;
import com.util.CookieUtil;
import com.util.FileUtil;
import com.util.LocalInformation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.util.PermissionUtil.isQMRead;
import static com.util.PermissionUtil.isQMWrite;

/**
 * 映射计算部分
 */
@Controller
@RequestMapping(value = "/compute_part",produces = "text/html;charset=UTF-8")
public class ComputePartController {
    //QM-input
    @RequestMapping(value = "/data_input_compute_QM",produces = "text/html;charset=UTF-8")
    public ModelAndView data_input_compute_QM(HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView();

        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        if (user_cookie_value != null && UserMetadata.OnlineUserId.containsKey(user_cookie_value)){
            UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value, LocalInformation.getTimeID());
            if (isQMWrite(user_cookie_value.split("wlcniubi")[2])){
                //进入数据导入界面
                int[] time= LocalInformation.getNowDate(new Date());
                modelAndView.addObject("time",time[0]+"-"+time[1]+"-"+time[2]);
                modelAndView.addObject("id",LocalInformation.getTimeID());
                modelAndView.addObject("author",user_cookie_value.split("wlcniubi")[1]);

                modelAndView.setViewName("data-input-compute-QM");
            }else {
                modelAndView.setViewName("Permission-Denied");
            }
        }else {
            modelAndView.setViewName("login");
        }
        return modelAndView;
    }

    @RequestMapping(value = "/data_save_compute_QM",produces = "text/html;charset=UTF-8")
    public ModelAndView data_save_compute_QM(HttpServletRequest request,
                                             @RequestParam(value = "part1")String part1,
                                             @RequestParam(value = "part2")String part2,
                                             @RequestParam(value = "part3")String part3,
                                             @RequestParam(value = "part4")String part4,
                                             @RequestParam(value = "calculateObject")String calculateObject,
                                             @RequestParam("frg_file") CommonsMultipartFile frg_file,
                                             @RequestParam("Active_track_file") CommonsMultipartFile Active_track_file,
                                             @RequestParam("Optimize_file") CommonsMultipartFile Optimize_file,
                                             @RequestParam("QM_out1_file") CommonsMultipartFile QM_out1_file,
                                             @RequestParam("QM_out2_file") CommonsMultipartFile QM_out2_file,
                                             @RequestParam("ESP_file") CommonsMultipartFile ESP_file) throws IOException {
        ModelAndView modelAndView = new ModelAndView();

        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        if (user_cookie_value != null && UserMetadata.OnlineUserId.containsKey(user_cookie_value)){
            UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value,LocalInformation.getTimeID());

            ArrayList<CommonsMultipartFile> files = new ArrayList<CommonsMultipartFile>(){
                {
                    add(frg_file);
                    add(Active_track_file);
                    add(Optimize_file);
                    add(QM_out1_file);
                    add(QM_out2_file);
                    add(ESP_file);
                }
            };
            int[] time= LocalInformation.getNowDate(new Date());
            String file_path = request.getSession().getServletContext().getRealPath("/")+"/file_data/compute_part/QM/"+time[0] + "_"+time[1]+"_"+time[2]+"/"+part1.split("wlcniubi")[0]+"_";
            String[] file_names = new String[6];
            for (int i = 0;i < 6;i++){
                if (!files.get(i).getOriginalFilename().equals("")){
                    file_names[i] = files.get(i).getOriginalFilename();
                    if (FileUtil.createFile(file_path + files.get(i).getOriginalFilename())){
                        File file = new File(file_path + files.get(i).getOriginalFilename());
                        files.get(i).transferTo(file);
                    }
                }else {
                    file_names[i] = "null";
                }
            }
            QmOperator.saveQmForm(part1,part2,part3,part4,file_names,calculateObject);

            modelAndView.setViewName("SystemHome");
        }else {
            modelAndView.setViewName("login");
        }
        return modelAndView;
    }

    @RequestMapping(value = "/QM_gaussFiles_process",produces = "text/html;charset=UTF-8")
    public void QM_gaussFile_process(@RequestParam("log_file") CommonsMultipartFile log_file,
                                      @RequestParam("dat_file") CommonsMultipartFile dat_file,
                                      HttpServletRequest request,
                                      HttpServletResponse response) throws Exception{
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        String author = user_cookie_value.split("wlcniubi")[1];
        String file_path = request.getSession().getServletContext().getRealPath("/")+"/temp_data/"+user_cookie_value.split("wlcniubi")[0]+"/";

        //dat_files_process
        String dat_file_path = file_path+dat_file.getOriginalFilename();
        if (!dat_file_path.equals(file_path) && FileUtil.createFile(dat_file_path)){
            File datFile=new File(dat_file_path);
            dat_file.transferTo(datFile);
        }
        //log_files_process
        String log_file_path = file_path+log_file.getOriginalFilename();
        if(FileUtil.createFile(log_file_path)){
            File logFile=new File(log_file_path);
            log_file.transferTo(logFile);
        }
        //process
        String status = QmOperator.processGaussFile(author,log_file_path,log_file.getOriginalFilename(),dat_file_path);
        //结果返回页面
//        response.setContentType("application/json");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out= null;
        out = response.getWriter();
        out.print(status);
        out.flush();
        out.close();
    }

    @RequestMapping(value = "/QM_gebfFiles_process",produces = "text/html;charset=UTF-8")
    public void QM_gebfFiles_process(@RequestParam("keys_file") CommonsMultipartFile keys_file,
                                     @RequestParam("cha_file") CommonsMultipartFile cha_file,
                                     @RequestParam("txt_file") CommonsMultipartFile txt_file,
                                     @RequestParam("log_file") CommonsMultipartFile log_file,
                                     @RequestParam("frg_file") CommonsMultipartFile frg_file,
                                     HttpServletRequest request,
                                     HttpServletResponse response) throws Exception{
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        String author = user_cookie_value.split("wlcniubi")[1];
        String authorId = user_cookie_value.split("wlcniubi")[0];
        String file_path = request.getSession().getServletContext().getRealPath("/")+"/temp_data/"+authorId+"/";

        //keys文件不能为空，且可以重复
        String keys_file_path = file_path+keys_file.getOriginalFilename();
        if (FileUtil.createFile(keys_file_path)){
            File keysFile = new File(keys_file_path);
            keys_file.transferTo(keysFile);
        }
        //cha文件不能为空，且可以重复
        String cha_file_path = file_path+cha_file.getOriginalFilename();
        if (FileUtil.createFile(cha_file_path)){
            File chaFile = new File(cha_file_path);
            cha_file.transferTo(chaFile);
        }
        //txt文件不能为空，且可以重复
        String txt_file_path = file_path+txt_file.getOriginalFilename();
        if (FileUtil.createFile(txt_file_path)){
            File txtFile = new File(txt_file_path);
            txt_file.transferTo(txtFile);
        }
        //log文件可以为空，且可以重复
        String log_file_path = file_path+log_file.getOriginalFilename();
        if (!log_file_path.equals(file_path) && FileUtil.createFile(log_file_path)){
            File logFile = new File(log_file_path);
            log_file.transferTo(logFile);
        }
        //frg文件不能为空，且可以重复
        int[] time= LocalInformation.getNowDate(new Date());
        String frg_file_path = request.getSession().getServletContext().getRealPath("/")+"/file_data/compute_part/QM/"+time[0] + "_"+time[1]+"_"+time[2]+"/"+authorId+"_"+frg_file.getOriginalFilename();
        if (FileUtil.createFile(frg_file_path)){
            File frgFile = new File(frg_file_path);
            frg_file.transferTo(frgFile);
        }
        //process
        QmOperator.processGebfFile(author,keys_file_path,cha_file_path,txt_file_path,frg_file_path,log_file_path);
        //返回页面
//        response.setContentType("application/json");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out= null;
        out = response.getWriter();
        out.print("success");
        out.flush();
        out.close();
    }

    @RequestMapping(value = "/QM_dmol3Files_process",produces = "text/html;charset=UTF-8")
    public void QM_dmol3Files_process(@RequestParam("cif_file") CommonsMultipartFile cif_file,
                                      @RequestParam("outmol_file") CommonsMultipartFile outmol_file,
                                      @RequestParam("dosOutmol_file") CommonsMultipartFile dosOutmol_file,
                                      @RequestParam("bandStrOutmol_file") CommonsMultipartFile bandStrOutmol_file,
                                      @RequestParam("calculateObject") String calculateObject,
                                     HttpServletRequest request,
                                     HttpServletResponse response) throws Exception{
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        String author = user_cookie_value.split("wlcniubi")[1];
        String file_path = request.getSession().getServletContext().getRealPath("/")+"/temp_data/"+user_cookie_value.split("wlcniubi")[0]+"/";

        //cif文件可以为空，且可以重复
        String cif_file_path = file_path+cif_file.getOriginalFilename();
        if (!cif_file_path.equals(file_path) && FileUtil.createFile(cif_file_path)){
            File cifFile = new File(cif_file_path);
            cif_file.transferTo(cifFile);
        }
        //outmol文件不能为空，且可以重复
        String outmol_file_path = file_path+outmol_file.getOriginalFilename();
        if (FileUtil.createFile(outmol_file_path)){
            File outmolFile = new File(outmol_file_path);
            outmol_file.transferTo(outmolFile);
        }
        //dosOutmol文件可以为空，且可以重复
        String dosOutmol_file_path = file_path+dosOutmol_file.getOriginalFilename();
        if (!dosOutmol_file_path.equals(file_path) && FileUtil.createFile(dosOutmol_file_path)){
            File dosOutmolFile = new File(dosOutmol_file_path);
            dosOutmol_file.transferTo(dosOutmolFile);
        }
        //bandStrOutmol文件可以为空，且可以重复
        String bandStrOutmol_file_path = file_path+bandStrOutmol_file.getOriginalFilename();
        if (!bandStrOutmol_file_path.equals(file_path) && FileUtil.createFile(bandStrOutmol_file_path)){
            File bandStrOutmolFile = new File(bandStrOutmol_file_path);
            bandStrOutmol_file.transferTo(bandStrOutmolFile);
        }

        //process
        QmOperator.processDmol3File(author,cif_file_path,outmol_file_path,dosOutmol_file_path,bandStrOutmol_file_path,calculateObject);

        //        response.setContentType("application/json");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out= null;
        out = response.getWriter();
        out.print("success");
        out.flush();
        out.close();
    }

    @RequestMapping(value = "/QM_castepFiles_process",produces = "text/html;charset=UTF-8")
    public void QM_castepFiles_process(@RequestParam("cif_file") CommonsMultipartFile cif_file,
                                       @RequestParam("castep_file") CommonsMultipartFile castep_file,
                                       @RequestParam("dosCastep_file") CommonsMultipartFile dosCastep_file,
                                       @RequestParam("bandStrCastep_file") CommonsMultipartFile bandStrCastep_file,
                                       @RequestParam("calculateObject") String calculateObject,
                                       HttpServletRequest request,
                                       HttpServletResponse response) throws Exception{
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        String author = user_cookie_value.split("wlcniubi")[1];
        String file_path = request.getSession().getServletContext().getRealPath("/")+"/temp_data/"+user_cookie_value.split("wlcniubi")[0]+"/";

        //cif文件可以为空，且可以重复
        String cif_file_path = file_path+cif_file.getOriginalFilename();
        if (!cif_file_path.equals(file_path)&&FileUtil.createFile(cif_file_path)){
            File cifFile = new File(cif_file_path);
            cif_file.transferTo(cifFile);
        }
        //castep文件不能为空，且可以重复
        String castep_file_path = file_path+castep_file.getOriginalFilename();
        if (FileUtil.createFile(castep_file_path)){
            File outmolFile = new File(castep_file_path);
            castep_file.transferTo(outmolFile);
        }
        //dosCastep文件可以为空，且可以重复
        String dosCastep_file_path = file_path+dosCastep_file.getOriginalFilename();
        if (!dosCastep_file_path.equals(file_path)&&FileUtil.createFile(dosCastep_file_path)){
            File dosCastepFile = new File(dosCastep_file_path);
            dosCastep_file.transferTo(dosCastepFile);
        }
        //bandStrCastep文件可以为空，且可以重复
        String bandStrCastep_file_path = file_path+bandStrCastep_file.getOriginalFilename();
        if (!bandStrCastep_file_path.equals(file_path)&&FileUtil.createFile(bandStrCastep_file_path)){
            File bandStrCastepFile = new File(bandStrCastep_file_path);
            bandStrCastep_file.transferTo(bandStrCastepFile);
        }

        //process
        QmOperator.processCastepFile(author,cif_file_path,castep_file_path,dosCastep_file_path,bandStrCastep_file_path,calculateObject);

        //        response.setContentType("application/json");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out= null;
        out = response.getWriter();
        out.print("success");
        out.flush();
        out.close();
    }

    @RequestMapping(value = "/QM_vaspFiles_process",produces = "text/html;charset=UTF-8")
    public void QM_vaspFiles_process(@RequestParam("incar_file") CommonsMultipartFile incar_file,
                                     @RequestParam("poscar_file") CommonsMultipartFile poscar_file,
                                     @RequestParam("potcar_file") CommonsMultipartFile potcar_file,
                                     @RequestParam("cif_file") CommonsMultipartFile cif_file,
                                     @RequestParam("kpoints_file") CommonsMultipartFile kpoints_file,
                                     @RequestParam("contcar_file") CommonsMultipartFile contcar_file,
                                     @RequestParam("outcar_file") CommonsMultipartFile outcar_file,
                                     @RequestParam("calculateObject") String calculateObject,
                                     HttpServletRequest request,
                                     HttpServletResponse response) throws Exception{
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        String author = user_cookie_value.split("wlcniubi")[1];
        String file_path = request.getSession().getServletContext().getRealPath("/")+"/temp_data/"+user_cookie_value.split("wlcniubi")[0]+"/";

        //incar文件可以为空，且可以重复
        String incar_file_path = file_path+incar_file.getOriginalFilename();
        if (!incar_file_path.equals(file_path)&&FileUtil.createFile(incar_file_path)){
            File incarFile = new File(incar_file_path);
            incar_file.transferTo(incarFile);
        }
        //poscar文件可以为空，且可以重复
        String poscar_file_path = file_path+poscar_file.getOriginalFilename();
        if (!poscar_file_path.equals(file_path)&&FileUtil.createFile(poscar_file_path)){
            File poscarFile = new File(poscar_file_path);
            poscar_file.transferTo(poscarFile);
        }
        //potcar文件可以为空，且可以重复
        String potcar_file_path = file_path+potcar_file.getOriginalFilename();
        if (!potcar_file_path.equals(file_path)&&FileUtil.createFile(potcar_file_path)){
            File potcarFile = new File(potcar_file_path);
            potcar_file.transferTo(potcarFile);
        }
        //cif文件可以为空，且可以重复
        String cif_file_path = file_path+cif_file.getOriginalFilename();
        if (!cif_file_path.equals(file_path)&&FileUtil.createFile(cif_file_path)){
            File cifFile = new File(cif_file_path);
            cif_file.transferTo(cifFile);
        }
        //kpoints文件可以为空，且可以重复
        String kpoints_file_path = file_path+kpoints_file.getOriginalFilename();
        if (!kpoints_file_path.equals(file_path)&&FileUtil.createFile(kpoints_file_path)){
            File kpointsFile = new File(kpoints_file_path);
            kpoints_file.transferTo(kpointsFile);
        }
        //contcar文件不能为空，且可以重复
        String contcar_file_path = file_path+contcar_file.getOriginalFilename();
        if (FileUtil.createFile(contcar_file_path)){
            File contcarFile = new File(contcar_file_path);
            contcar_file.transferTo(contcarFile);
        }
        //outcar文件不能为空，且可以重复
        String outcar_file_path = file_path+outcar_file.getOriginalFilename();
        if (FileUtil.createFile(outcar_file_path)){
            File outcarFile = new File(outcar_file_path);
            outcar_file.transferTo(outcarFile);
        }

        //process
        QmOperator.processVaspFile(author,incar_file_path,poscar_file_path,potcar_file_path,cif_file_path,kpoints_file_path,contcar_file_path,outcar_file_path,calculateObject);

        //        response.setContentType("application/json");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out= null;
        out = response.getWriter();
        out.print("success");
        out.flush();
        out.close();
    }

    //QM-search
    @RequestMapping(value = "/data_search_compute_QM",produces = "text/html;charset=UTF-8")
    public ModelAndView data_search_compute_QM(HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView();

        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        if (user_cookie_value != null && UserMetadata.OnlineUserId.containsKey(user_cookie_value)){
            UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value,LocalInformation.getTimeID());
            if (isQMRead(user_cookie_value.split("wlcniubi")[2])){
                //进入数据查找界面
                modelAndView.setViewName("data-search-compute-QM");
            }else {
                modelAndView.setViewName("Permission-Denied");
            }
        }else {
            modelAndView.setViewName("login");
        }

        return modelAndView;
    }

    @RequestMapping(value = "/keyword_search_QM",produces = "text/html;charset=UTF-8")
    public void keyword_search_QM(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value,LocalInformation.getTimeID());
        String projectPath = request.getSession().getServletContext().getRealPath("/");

        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out=response.getWriter();
        out.println(UserOperator.setSearchResult(user_cookie_value,projectPath,request.getParameter("base"),request.getParameter("keyword")));
        out.flush();
        out.close();
    }

    //@RequestParam(value = "qm_select_result")String select_data_id,
    @RequestMapping(value = "/generate_qm_select_result",produces = "text/html;charset=UTF-8")
    public ModelAndView generate_qm_select_result(HttpServletRequest request) throws IOException{

        String select_data_id = request.getParameter("qm_select_result");

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("template-searchTable");

        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value,LocalInformation.getTimeID());
        String projectPath = request.getSession().getServletContext().getRealPath("/");                      //Path

        String table_data = UserOperator.getSearchResult(user_cookie_value,projectPath,select_data_id);

        String table_title = StringUtils.join(QmDao.getTiltlName(select_data_id.substring(0,17)).toArray(),"wlcniubi");


        modelAndView.addObject("table_data",table_data);
        modelAndView.addObject("table_title", table_title); //取第一个id区分溶质溶剂和晶体
        modelAndView.addObject("data_type", "QM");

        return modelAndView;
    }

}
